<template>
  <div>
    <BasicTable
      @register="registerTable"
      :can-resize="true"
      :bordered="true"
      :striped="false"
      :data-source="tableData.data"
    >
      <template #toolbar>
        <a-button type="primary" @click="onAddSecurityLedger"> 新增 </a-button>
        <a-button @click="aoaToExcel"> 导出Excel </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditSecurityLedger.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: onDeleteSecurityLedger.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>

    <addOrUpdate @register="registerAddOrUpdateForm" @success="afterSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, onBeforeMount, onUnmounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { Tag } from 'ant-design-vue';

  import { useMessage } from '/@/hooks/web/useMessage';

  import { aoaToSheetXlsx } from '/@/components/Excel';

  import { getAllSecurityLedger, deleteSecurityLedger } from '/@/api/cms/securityLedger';
  import { securityLedgerTableColumns, exportArrHeader } from './SecurityLedger.data';

  //引入子组件
  import addOrUpdate from './AddOrUpdate.vue';

  //使用modal弹出窗口
  import { useModal } from '/@/components/Modal';
  const { createMessage } = useMessage();

  const [registerAddOrUpdateForm, { openModal: openAddOrUpdateForm }] = useModal();

  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';

  export default defineComponent({
    name: 'SecurityLedgerManagement',
    components: { Tag, BasicTable, TableAction, addOrUpdate },
    setup() {
      const moduleTitle = ref('安全台历管理');

      //导出数组数据
      let exportArrData = ref([]);
      function aoaToExcel() {
        console.log('导出数据', exportArrData);
        // 保证data顺序与header一致
        aoaToSheetXlsx({
          data: exportArrData, //数组数据
          header: [
            '发生日期',
            '责任分类',
            'ID',
            '责任单位',
            '事故分类',
            '障碍等级',
            '事故详情内容',
          ], //表头
          filename: '安全台历.xlsx', //导出的文件名
        });
      }

      //表格数据
      const tableData = reactive({
        data: [],
      });

      /**
       * 请求后台查询接口返回数据显示
       */
      const [registerTable, { reload }] = useTable({
        title: moduleTitle.value,
        // api: getAllSecurityLedger,
        columns: securityLedgerTableColumns, //表头数据
        showTableSetting: true, //是否显示表格设置
        showIndexColumn: true,
        actionColumn: {
          width: 100,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        pagination: true, //分页
      });

      onBeforeMount(() => {
        console.log('DOM即将挂载');
        query();
      });
      onUnmounted(() => {
        console.log('销毁完毕');
      });

      /**
       * 查询安全台历
       */
      function query() {
        if (tableData.data.length > 0) {
          tableData.data = [];
        }
        getAllSecurityLedger()
          .then((res) => {
            console.log('res', res);
            res.forEach((val) => {
              tableData.data.push(val);
            });

            //导出Excel数据
            exportArrData = tableData.data.map((item) => {
              return Object.keys(item).map((key) => item[key]);
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            // createMessage.error(ex.msg);
          });
      }

      /**
       * 打开新增窗口
       */
      function onAddSecurityLedger() {
        //使用props传递数据至子组件，在data参数中指定
        let propsData: QcUnifyTransToChildProps = {
          moduleName: moduleTitle.value,
          operateType: OperationTypeEnum.ADD,
        };

        openAddOrUpdateForm(true, propsData);
      }

      /**
       * 打开编辑窗口
       */
      function onEditSecurityLedger(record: Recordable) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: moduleTitle.value,
          operateType: OperationTypeEnum.EDIT,
          dataId: record.id,
        };
        openAddOrUpdateForm(true, propsData);
      }

      /**
       * 删除
       */
      function onDeleteSecurityLedger(record: Recordable) {
        deleteSecurityLedger(record.id)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              afterSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        // reload();
        query();
      }

      return {
        query,
        moduleTitle,
        registerTable,
        afterSuccess,
        registerAddOrUpdateForm,
        onAddSecurityLedger,
        onEditSecurityLedger,
        onDeleteSecurityLedger,
        tableData,
        aoaToExcel,
      };
    },
  });
</script>
